#!/bin/bash
#=======================
# Author : Ali Moradzade
# Created: 2022/01/15
#=======================

# convert pdftk bookmarks to json file

function usage {
	echo "Usage: $1 [pdf-file] [output-json-file-name]"
}

function checkpdffile {
	local pdf_file_name=$1
	if ! [ -f "$pdf_file_name" ]
	then
		echo "pdf file: $pdf_file_name, does not exist. aborting ..."
		exit
	fi
}

function checkoutfile {
	local output_file_name=$1
	if [ -f "$output_file_name" ]
	then
		echo "$output_file_name exists."
		read -n 1 -p "do you want to overwrite it? (Y/n) "
		echo
		case "$REPLY" in
			Y)
				echo "overwriting $output_file_name ..."
				echo -n "" > $output_file_name
				;;
			*)
				echo "aborting ..."
				exit
			;;
		esac
	fi
}

if [ "$#" -ne 2 ]
then
	usage $(basename $0)
	exit
fi

checkpdffile $1
checkoutfile $2

pdf_file_name=$1
output_file_name=$2

temp_file=$(mktemp tempXXXXX)

echo "process started ..."
pdftk $pdf_file_name dump_data output | grep Bookmark | while read begin; read title; read level; read page;
do
	page=$(echo "$page" | sed 's/BookmarkPageNumber: //')
	title=$(echo "$title" | sed 's/BookmarkTitle: //')
	level=$(echo "$level" | sed 's/BookmarkLevel: //')

	echo -e "\t{\"title\": \"$title\", \"page\": $page, \"level\": $level}"
done >> $temp_file

# Link: https://stackoverflow.com/questions/35021524/how-can-i-add-a-comma-at-the-end-of-every-line-except-the-last-line/35021663
sed -e '1s/^/[/;$!s/$/,/;$s/$/]/' $temp_file | jq '.' > $output_file_name
rm $temp_file

echo
echo "process finished successfully"
echo "your output json file is in: $output_file_name"
